package ThreadPoolExecutor;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class MyThreadPoolExecutor{
    private List<Thread> list = new ArrayList<>();//用来储存线程

    //用来保存任务的对来（阻塞队列）
    private BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<>(1000);

    //通过n指定创建多少个线程
    public MyThreadPoolExecutor(int n){
        for (int i = 0; i < n; i++) {
            Thread t = new Thread(()->{
                //线程要做的就是把任务队列中的任务不停的取出来，并且执行
                while (true){
                    try {
                        //有阻塞功能，如果队列为空，take就会阻塞
                        Runnable runnable = blockingQueue.take();

                        //取出一个任务就执行一个
                        runnable.run();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });

            t.start();
            list.add(t);
        }
    }

    public void submit(Runnable runnable) throws InterruptedException {
        blockingQueue.put(runnable);
    }
}
public class demo {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPoolExecutor myThreadPoolExecutor =  new MyThreadPoolExecutor(4);
        for (int i = 0; i < 1000; i++) {
            int n = i;
            myThreadPoolExecutor.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("执行任务" + n + ", 当前线程为：" + Thread.currentThread().getName());
                                                //这里用n不用i是因为常量捕获
                }
            });
        }
    }
}
